package se581.banker.util;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * Writes out the query responses received by the QueryClients
 * 
 * @author mmichalak
 *
 */
public class OutputFileWriterUtil {
	static final Logger logger = Logger.getLogger(OutputFileWriterUtil.class.getName());
	
	BufferedWriter OUT = null;
	
	public OutputFileWriterUtil(String filename) {
		super();
		try {
			OUT = new BufferedWriter(new FileWriter("c:\\SE480\\" + filename));
		} catch (IOException e) {
			logger.error("Unable to create TrackerOutput file!");
			e.printStackTrace();
		}
	}
	
	public void writeToFile(String message) {
        try {
        	if (message == null) {
        		logger.error("Output message is null");
        		return;
        	}
        	OUT.write(message);
        	OUT.write("\n\n");
        	OUT.flush();
		} catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
	
	/**
	 * No blank line between lines
	 * @param message
	 */
	public void writeToFileWOBlanks(String message) {
        try {
        	if (message == null) {
        		logger.error("Output message is null");
        		return;
        	}
        	OUT.write(message);
        	OUT.write("\n");
        	OUT.flush();
		} catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
    }
	    
    public void close() {
        try {
        	OUT.close();
		} catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

    public void setOutputFile(String filename) {
		try {
			OUT = new BufferedWriter(new FileWriter("c:\\SE480\\" + filename));
		} catch (IOException e) {
			logger.error("Unable to create TrackerOutput file!");
			e.printStackTrace();
		}	
    }
}
